//    Openbravo POS is a point of sales application designed for touch screens.
//    Copyright (C) 2007-2009 Openbravo, S.L.
//    http://www.openbravo.com/product/pos
//
//    This file is part of Openbravo POS.
//
//    Openbravo POS is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Openbravo POS is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Openbravo POS.  If not, see <http://www.gnu.org/licenses/>.

package com.openbravo.pos.sales.restaurant;

import cn.ekuma.epos.bean.util.FloorExtHelper;
import cn.ekuma.epos.bean.util.sale.TicketWarp;
import cn.ekuma.epos.datalogic.I_DataLogicCustomers;
import cn.ekuma.epos.datalogic.I_DataLogicSystem;

import com.openbravo.bean.sales.KitchenWorkLine;
import com.openbravo.bean.Place;
import com.openbravo.bean.PlaceState;
import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.bean.FloorExt;
import com.openbravo.pos.base.AppView;

import cn.ekuma.epos.datalogic.I_DataLogicReceipts;


import com.openbravo.bean.sales.Ticket;

import java.util.*;
import java.util.List;
import java.util.Timer;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

import com.openbravo.pos.printer.DevicePrinter;
import com.openbravo.pos.printer.DeviceTicket;
import com.openbravo.pos.printer.TicketParser;
import com.openbravo.pos.printer.TicketPrinterException;
import com.openbravo.pos.printer.screen.DevicePrinterPanel;
import com.openbravo.pos.sales.*;
import com.openbravo.pos.scripting.ScriptEngine;
import com.openbravo.pos.scripting.ScriptException;
import com.openbravo.pos.scripting.ScriptFactory;
import com.openbravo.pos.util.JPanelDrawing;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.data.gui.NullIcon;
import com.openbravo.data.loader.ImageUtils;
import com.openbravo.format.Formats;
import com.openbravo.bean.infobean.CustomerInfo;

public abstract class AbstractJTicketsBagRestaurant extends JTicketsBag {

    protected static final Icon ICO_OCU = new ImageIcon(AbstractJTicketsBagRestaurant.class.getResource("/com/openbravo/images/edit_group.png"));
    protected static final Icon ICO_FRE = new NullIcon(22, 22);

    protected java.util.List<Place> m_aplaces;
    protected java.util.List<FloorExt> m_afloors;

    protected JTicketsBagRestaurantRes m_jreservations;

    protected Place m_PlaceCurrent;
    protected JTabbedPane floors;
    // State vars
    protected Place m_PlaceClipboard;
    protected CustomerInfo customerInfo;

    protected I_DataLogicReceipts dlReceipts = null;
    protected I_DataLogicCustomers dlCustomers = null;

    protected Map<Place, JButton> placeButtonMap;
    protected Map<String, JPanelDrawing> floorMap;

    protected JViewKitchenLineDialog viewKickenLineDialog;
    private I_DataLogicSystem dlSystem;
    private Timer timer;

    protected Map<String, PlaceState> placeStateMap;
    private boolean isInit;

    private boolean reFlushFlag = true;
    protected boolean clickStateFlag = false;//默认是查询
    private String sresource;
    private String sresourcename;
    TicketParser m_TTP;
    private DevicePrinter dpt;

    public AbstractJTicketsBagRestaurant() {
        initComponents();
    }

    /**
     * Creates new form JTicketsBagRestaurantKeyBoard
     */
    public AbstractJTicketsBagRestaurant(AppView app, TicketsEditor panelticket, String placeStateSrcName) {

        super(app, panelticket);
        sresourcename = placeStateSrcName;
        dlReceipts = panelticket.getDlReceipts();
        dlCustomers = panelticket.getDlCustomers();
        dlSystem = panelticket.getDlSystem();

        DeviceTicket deviceTicket = new DeviceTicket();
        m_TTP = new TicketParser(deviceTicket, dlSystem);
        m_PlaceCurrent = null;
        m_PlaceClipboard = null;
        customerInfo = null;
        floors = null;
        placeButtonMap = new HashMap<Place, JButton>();
        floorMap = new HashMap<String, JPanelDrawing>();
        placeStateMap = new HashMap<String, PlaceState>();
        try {
            m_afloors = m_dlSales.list(FloorExt.class);
        } catch (BasicException eD) {
            m_afloors = new ArrayList<FloorExt>();
        }
        try {
            m_aplaces = m_dlSales.list(Place.class);
        } catch (BasicException e) {
            m_aplaces = new ArrayList<Place>();
        }

        initComponents();
        dpt = deviceTicket.getDevicePrinter("1");
        placeStatePanel.add(dpt.getPrinterComponent(), BorderLayout.CENTER);
        JPanelDrawing floorPanel;
        // add the Floors containers
        if (m_afloors.size() > 1) {
            // A tab container for 2 or more floors
            JTabbedPane jTabFloors = new JTabbedPane();
            floors = jTabFloors;
            jTabFloors.applyComponentOrientation(getComponentOrientation());
            jTabFloors.setBorder(new javax.swing.border.EmptyBorder(new Insets(5, 5, 5, 5)));
            jTabFloors.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
            jTabFloors.setFocusable(false);
            jTabFloors.setRequestFocusEnabled(false);
            m_jPanelMap.add(jTabFloors, BorderLayout.CENTER);


            for (FloorExt f : m_afloors) {
                floorPanel = new JPanelDrawing(ImageUtils.readImage(f.getImage()));
                floorPanel.applyComponentOrientation(getComponentOrientation());

                JScrollPane jScrCont = new JScrollPane();
                jScrCont.applyComponentOrientation(getComponentOrientation());
                JPanel jPanCont = new JPanel();
                jPanCont.applyComponentOrientation(getComponentOrientation());

                jTabFloors.addTab(f.getName(), FloorExtHelper.getIcon(f), jScrCont);
                jScrCont.setViewportView(jPanCont);
                jPanCont.add(floorPanel);
                floorMap.put(f.getID(), floorPanel);
            }
            KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
            ActionListener actionListener = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    upKeyProc();
                }
            };
            jTabFloors.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

            stroke = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
            actionListener = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    downKeyProc();
                }
            };
            jTabFloors.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);


        } else if (m_afloors.size() == 1) {
            // Just a frame for 1 floor
            FloorExt f = m_afloors.get(0);
            floorPanel = new JPanelDrawing(ImageUtils.readImage(f.getImage()));
            floorPanel.applyComponentOrientation(getComponentOrientation());

            JPanel jPlaces = new JPanel();
            jPlaces.applyComponentOrientation(getComponentOrientation());
            jPlaces.setLayout(new BorderLayout());
            jPlaces.setBorder(new javax.swing.border.CompoundBorder(
                    new javax.swing.border.EmptyBorder(new Insets(5, 5, 5, 5)),
                    new javax.swing.border.TitledBorder(f.getName())));

            JScrollPane jScrCont = new JScrollPane();
            jScrCont.applyComponentOrientation(getComponentOrientation());
            JPanel jPanCont = new JPanel();
            jPanCont.applyComponentOrientation(getComponentOrientation());

            // jPlaces.setLayout(new FlowLayout());           
            m_jPanelMap.add(jPlaces, BorderLayout.CENTER);
            jPlaces.add(jScrCont, BorderLayout.CENTER);
            jScrCont.setViewportView(jPanCont);
            jPanCont.add(floorPanel);
            floorMap.put(f.getID(), floorPanel);
        }

        // Add all the Table buttons.
        FloorExt currfloor = null;


        for (Place pl : m_aplaces) {
            int iFloor = 0;

            if (currfloor == null || !currfloor.getID().equals(pl.getFloor())) {
                // Look for a new floor
                do {
                    currfloor = m_afloors.get(iFloor++);
                } while (!currfloor.getID().equals(pl.getFloor()));
            }

            JButton m_btn = new JButton();
            m_btn.setFocusPainted(false);
            m_btn.setFocusable(false);
            m_btn.setRequestFocusEnabled(false);
            m_btn.setHorizontalTextPosition(SwingConstants.CENTER);
            m_btn.setVerticalTextPosition(SwingConstants.BOTTOM);
            m_btn.setIcon(ICO_FRE);
            m_btn.setText(pl.getName());

            Dimension d = m_btn.getPreferredSize();
            m_btn.setBounds(pl.getX() - d.width / 2, pl.getY() - d.height / 2, d.width, d.height);
            m_btn.addActionListener(getPlaceActionListener(pl));
            placeButtonMap.put(pl, m_btn);
            floorMap.get(currfloor.getID()).add(m_btn);
        }

        // Add the reservations panel
        m_jreservations = new JTicketsBagRestaurantRes(app, this, dlCustomers, m_dlSales);
        JSelectTable.requestFocus();
        add(m_jreservations, "res");
    }

    protected abstract ActionListener getPlaceActionListener(Place pl);

    protected void upKeyProc() {

        int selected = floors.getSelectedIndex();
        selected -= 1;
        if (selected < 0) {
            selected = m_afloors.size() - 1;
        }
        floors.setSelectedIndex(selected);
    }

    protected void downKeyProc() {
        int selected = floors.getSelectedIndex();
        selected += 1;
        if (selected > m_afloors.size() - 1) {
            selected = 0;
        }
        floors.setSelectedIndex(selected);
    }


    public void activate() {

        // precondicion es que no tenemos ticket activado ni ticket en el panel
        isInit = true;
        m_PlaceClipboard = null;
        customerInfo = null;
        String refesh = m_App.getProperties().getProperty(SaleConfig.RESTAURANT_REFRESH_RATE);
        int refeshI = 5000;
        if (refesh != null)
            refeshI = Integer.valueOf(refesh);
        sresource = dlSystem.getResourceAsXML(sresourcename);
        if (sresource == null || sresource.isEmpty()) {
            placeStatePanel.setVisible(false);
        }


        loadPlaceStates();
        printState();

        m_panelticket.setActiveTicket(null, null, false);
        ((RestaurantTicketBag) getBagComponent()).activate();

        showView("map"); // arrancamos en la vista de las mesas.

        timer = new java.util.Timer(true);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                java.awt.EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        if (reFlushFlag) {
                            loadPlaceStates();
                            printState();
                        }
                    }
                });
            }

        }, 1000, refeshI);

        // postcondicion es que tenemos ticket activado aqui y ticket en el panel
    }

    public boolean deactivate() {

        // precondicion es que tenemos ticket activado aqui y ticket en el panel
        timer.cancel();
        if (viewTables()) {

            // borramos el clipboard
            m_PlaceClipboard = null;
            customerInfo = null;

            // guardamos el ticket
            if (m_PlaceCurrent != null) {

                try {
                    dlReceipts.updateSharedTicketAndUnLocked(m_PlaceCurrent.getId(), m_panelticket.getActiveTicket());
                    dlReceipts.updateTicketState(m_PlaceCurrent.getId(), KitchenWorkLine.TICKETSTATE_background);
                } catch (BasicException e) {
                    new MessageInf(e).show(this);
                }

                m_PlaceCurrent = null;
            }

            // desactivamos cositas.
            printState();
            m_panelticket.setActiveTicket(null, null, false);

            return true;
        } else {
            return false;
        }

        // postcondicion es que no tenemos ticket activado
    }


    public JComponent getNullComponent() {
        return this;
    }

    public void moveTicket() {

        // guardamos el ticket
        if (m_PlaceCurrent != null) {

            try {
                dlReceipts.updateSharedTicketAndUnLocked(m_PlaceCurrent.getId(), m_panelticket.getActiveTicket());
            } catch (BasicException e) {
                new MessageInf(e).show(this);
            }

            // me guardo el ticket que quiero copiar.
            m_PlaceClipboard = m_PlaceCurrent;
            customerInfo = null;
            m_PlaceCurrent = null;
        }

        printState();
        m_panelticket.setActiveTicket(null, null, false);
    }

    public boolean viewTables(CustomerInfo c) {
        // deberiamos comprobar si estamos en reservations o en tables...
        if (m_jreservations.deactivate()) {
            showView("map"); // arrancamos en la vista de las mesas.

            m_PlaceClipboard = null;
            customerInfo = c;
            printState();

            return true;
        } else {
            return false;
        }
    }

    public boolean viewTables() {
        return viewTables(null);
    }

    PlaceState currentPlaceState;
    Date befineTime;

    public void newTicket() {
        // guardamos el ticket
        if (m_PlaceCurrent != null) {
            try {
                dlReceipts.updateSharedTicketAndUnLocked(m_PlaceCurrent.getId(), m_panelticket.getActiveTicket());
                dlReceipts.updateTicketState(m_PlaceCurrent.getId(), KitchenWorkLine.TICKETSTATE_background);
            } catch (BasicException e) {
                new MessageInf(e).show(this); // maybe other guy deleted it
            }

            m_PlaceCurrent = null;
        }
        printState();
        m_panelticket.setActiveTicket(null, null, false);
    }

    public void deleteTicket() {
        if (m_PlaceCurrent != null) {
            try {
                clearPlace(m_PlaceCurrent);
            } catch (BasicException e) {
                new MessageInf(e).show(this);
            }
            setPlaceSelect(m_PlaceCurrent, false);
            m_PlaceCurrent = null;
        }

        printState();
        m_panelticket.setActiveTicket(null, null, false);
    }

    public void loadPlaceStates() {
        reFlushFlag = false;
        List<PlaceState> placeStates = null;
        try {
            /**
             * Set<String> atickets = new HashSet<String>();
             java.util.List<SharedTicketInfo> l = dlReceipts.getSharedTicketList(m_App.getInventoryLocation());
             for (SharedTicketInfo ticket : l) {
             atickets.add(ticket.getId());
             }
             boolean flag=atickets.contains(table.getId());
             **/

            if (isInit) {
                befineTime = new Date();
                placeStates = m_dlSales.list(PlaceState.class);
            } else {
                Date temp = new Date();
                placeStates = dlReceipts.loadPlacesStateBetween(befineTime, temp);
                befineTime = temp;
            }

        } catch (BasicException e) {
            new MessageInf(e).show(this);
            placeStates = new ArrayList<PlaceState>();
        }
        for (PlaceState placeState : placeStates) {
            this.placeStateMap.put(placeState.getPlaceId(), placeState);
            System.out.println("找到更新号：" + placeState.getPlaceId());
        }

        if (isInit) {
            for (Place table : m_aplaces) {
                PlaceState p = placeStateMap.get(table.getId());
                if (p == null) {
                    p = new PlaceState();
                    p.setPlaceId(table.getId());
                    try {
                        m_dlSales.insert(p);
                    } catch (BasicException e) {
                        new MessageInf(e).show(this);
                    }
                    placeStateMap.put(table.getId(), p);
                }
            }
            isInit = false;
        }
        for (Place place : m_aplaces) {
            PlaceState p = placeStateMap.get(place.getId());
            setPlaceSelect(place, !p.hasEnable());
        }
        reFlushFlag = true;
    }

    protected void printState() {

        if (m_PlaceClipboard == null) {
            if (customerInfo == null) {
                // Select a table
                m_jText.setText(null);
                // Enable all tables
                for (Place place : m_aplaces) {
                    this.placeButtonMap.get(place).setEnabled(true);
                }
                m_jbtnReservations.setEnabled(true);
                tgChangeStateButton.setEnabled(true);
            } else {
                // receive a customerInfo
                m_jText.setText(AppLocal.getIntString("label.restaurantcustomer", new Object[]{customerInfo.getName()}));
                // Enable all tables
                for (Place place : m_aplaces) {
                    PlaceState p = placeStateMap.get(place.getId());
                    this.placeButtonMap.get(place).setEnabled(p.hasEnable());
                }
                m_jbtnReservations.setEnabled(false);
                tgChangeStateButton.setEnabled(false);

            }
        } else {
            // Moving or merging the receipt to another table
            m_jText.setText(AppLocal.getIntString("label.restaurantmove", new Object[]{m_PlaceClipboard.getName()}));
            // Enable all empty tables and origin table.
            for (Place place : m_aplaces) {
                placeButtonMap.get(place).setEnabled(true);
            }
            m_jbtnReservations.setEnabled(false);
            tgChangeStateButton.setEnabled(false);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JSelectTable.setText("");
                JSelectTable.requestFocus();
            }
        });
    }

    protected Ticket getTicketInfo(Place place) {
        try {
            return dlReceipts.getSharedTicket(place.getId());
        } catch (BasicException e) {
            new MessageInf(e).show(this);
            return null;
        }
    }

    protected void setActivePlace(Place place, Ticket ticket) {
        m_PlaceCurrent = place;
        m_panelticket.setActiveTicket(ticket, m_PlaceCurrent.getName(), true);
    }

    protected void showView(String view) {
        CardLayout cl = (CardLayout) (getLayout());
        cl.show(this, view);
        if (view.equalsIgnoreCase("map")) {
            JSelectTable.requestFocus();
        }

    }


    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        m_jPanelMap = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        m_jbtnReservations = new javax.swing.JButton();
        m_jbtnRefresh = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        JSelectTable = new javax.swing.JTextField();
        m_jText = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jGroupManage = new javax.swing.JButton();

        setLayout(new java.awt.CardLayout());

        m_jPanelMap.setLayout(new java.awt.BorderLayout());

        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        m_jbtnReservations.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/date.png"))); // NOI18N
        m_jbtnReservations.setText(AppLocal.getIntString("button.reservations")); // NOI18N
        m_jbtnReservations.setFocusPainted(false);
        m_jbtnReservations.setFocusable(false);
        m_jbtnReservations.setMargin(new java.awt.Insets(8, 14, 8, 14));
        m_jbtnReservations.setRequestFocusEnabled(false);
        m_jbtnReservations.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jbtnReservationsActionPerformed(evt);
            }
        });
        jPanel2.add(m_jbtnReservations);

        m_jbtnRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/reload.png"))); // NOI18N
        m_jbtnRefresh.setText(AppLocal.getIntString("button.reloadticket")); // NOI18N
        m_jbtnRefresh.setFocusPainted(false);
        m_jbtnRefresh.setFocusable(false);
        m_jbtnRefresh.setMargin(new java.awt.Insets(8, 14, 8, 14));
        m_jbtnRefresh.setRequestFocusEnabled(false);
        m_jbtnRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jbtnRefreshActionPerformed(evt);
            }
        });
        jPanel2.add(m_jbtnRefresh);

        jPanel3.setFocusable(false);
        jPanel3.setLayout(new java.awt.BorderLayout());

        JSelectTable.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        JSelectTable.setFocusCycleRoot(true);
        JSelectTable.setPreferredSize(new java.awt.Dimension(80, 23));
        JSelectTable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JSelectTableActionPerformed(evt);
            }
        });
        jPanel3.add(JSelectTable, java.awt.BorderLayout.CENTER);

        jPanel2.add(jPanel3);
        jPanel2.add(m_jText);

        jGroupManage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/kuser.png"))); // NOI18N
        jGroupManage.setText(AppLocal.getIntString("button.groupManage")); // NOI18N
        jGroupManage.setMargin(new java.awt.Insets(8, 14, 8, 14));
        jGroupManage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                //jGroupManageActionPerformed(evt);
            }
        });
        //jPanel4.add(jGroupManage);

        jPanel2.add(jPanel4);

        jPanel1.add(jPanel2, java.awt.BorderLayout.LINE_START);

        tgChangeStateButton = new JToggleButton("快速入单");
        tgChangeStateButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                clickStateFlag = !clickStateFlag;
            }
        });
        tgChangeStateButton.setMargin(new Insets(8, 14, 8, 14));
        jPanel2.add(tgChangeStateButton);

        m_jPanelMap.add(jPanel1, java.awt.BorderLayout.NORTH);

        add(m_jPanelMap, "map");

        countPanel = new JPanel();
        m_jPanelMap.add(countPanel, BorderLayout.SOUTH);
        countPanel.setLayout(new BorderLayout(0, 0));

        lblNewLabel = new JLabel("统计出所有的满座，空座，人员，级其它状态的信息");
        countPanel.add(lblNewLabel);

        placeStatePanel = new JPanel();
        placeStatePanel.setPreferredSize(new Dimension(250, 10));
        m_jPanelMap.add(placeStatePanel, BorderLayout.EAST);
        placeStatePanel.setLayout(new BorderLayout(0, 0));

        textPane = new JTextPane();
        textPane.setPreferredSize(new Dimension(6, 100));
        textPane.setFocusable(false);
        textPane.setFocusTraversalKeysEnabled(false);
        textPane.setFocusCycleRoot(false);
        textPane.setEditable(false);
        textPane.setText("用于显示出当前先择的相关信息，如桌号，入座时间，营业员，菜品状态");
        placeStatePanel.add(textPane, BorderLayout.SOUTH);
    }// </editor-fold>//GEN-END:initComponents

    private void m_jbtnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jbtnRefreshActionPerformed
        m_PlaceClipboard = null;
        customerInfo = null;
        loadPlaceStates();
        printState();

    }//GEN-LAST:event_m_jbtnRefreshActionPerformed

    private void m_jbtnReservationsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jbtnReservationsActionPerformed

        showView("res");
        m_jreservations.activate();

    }//GEN-LAST:event_m_jbtnReservationsActionPerformed

    private void JSelectTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JSelectTableActionPerformed
        try {
            String tableID = (String) Formats.STRING.parseValue(JSelectTable.getText(), "");
            if (tableID.isEmpty())
                return;
            for (Place place : m_aplaces) {
                if (place.getId().equalsIgnoreCase(tableID) && placeButtonMap.get(place).isEnabled()) {
                    placeButtonMap.get(place).doClick();
                    return;
                }
            }
        } catch (BasicException ex) {
        }
    }//GEN-LAST:event_JSelectTableActionPerformed

    private void jGroupManageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jGroupManageActionPerformed
        m_PlaceClipboard = null;
        customerInfo = null;
        m_PlaceCurrent = null;
        m_panelticket.setActiveTicket(null, null, false);
        JPlaceGroupSplit groupSplit = JPlaceGroupSplit.getDialog(getComponent(), dlSystem, null);
        groupSplit.setVisible(true);
        if (groupSplit.isMustReflush()) {
            printState();
        }
    }//GEN-LAST:event_jGroupManageActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField JSelectTable;
    private javax.swing.JButton jGroupManage;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel m_jPanelMap;
    private javax.swing.JLabel m_jText;
    private javax.swing.JButton m_jbtnRefresh;
    private javax.swing.JButton m_jbtnReservations;
    private JToggleButton tgChangeStateButton;
    private JPanel countPanel;
    private JPanel placeStatePanel;
    private JLabel lblNewLabel;
    private JTextPane textPane;
    // End of variables declaration//GEN-END:variables


    public abstract JComponent getComponent();

    protected void setPlaceSelect(Place place, boolean flag) {
        //place.setPeople(flag);
        JButton selectBut = placeButtonMap.get(place);
        selectBut.setIcon(flag ? ICO_OCU : ICO_FRE);
    }

    @Override
    public void flushTicket() {
        reFlushFlag = false;
        if (m_PlaceCurrent != null) {
            String id = m_PlaceCurrent.getId();
            try {
                dlReceipts.updateTicketState(id, KitchenWorkLine.TICKETSTATE_completed);
                clearPlace(m_PlaceCurrent);
            } catch (BasicException e) {
                new MessageInf(e).show(this);
            }
            setPlaceSelect(m_PlaceCurrent, false);
            m_PlaceCurrent = null;
        }
        printState();
        m_panelticket.setActiveTicket(null, null, false);
        reFlushFlag = true;
    }


    public void sendToKitchen() {
        if (m_PlaceCurrent != null) {
            String id = m_PlaceCurrent.getId();
            try {
                dlReceipts.sendToKitchen(id, m_panelticket.getActiveTicket());
            } catch (BasicException e) {
                new MessageInf(e).show(this);
            }
        }
    }

    public void viewKitchLine() {
        if (viewKickenLineDialog == null) {
            viewKickenLineDialog = JViewKitchenLineDialog.newJDialog(this, dlSystem.getResourceAsXML("Kitchen.Lines.View"));
        }
        try {
            viewKickenLineDialog.loadData(dlReceipts.listKitchenWorkLineByTicketID(m_PlaceCurrent.getId()));
        } catch (BasicException e) {
            new MessageInf(e).show(this);
        }
    }

    public void urgentToKitch() {
        if (m_PlaceCurrent != null)
            try {
                dlReceipts.urgentToKitch(m_PlaceCurrent.getId());
            } catch (BasicException e) {
                new MessageInf(e).show(this);
            }
    }


    protected void clearPlace(Place p) throws BasicException {
        dlReceipts.deleteSharedTicket(p.getId());
        PlaceState placeState = placeStateMap.get(p.getId());
        placeState.clear();
        placeState.setChangeTime(new Date());
        m_dlSales.update(placeState);
    }

    protected void printPlaceState(Place p, Ticket t) {
        if (sresource == null || p == null) {
            textPane.setText("没有内容可显示");
            return;
        }
        dpt.reset();
        PlaceState placeState = placeStateMap.get(p.getId());
        try {
            ScriptEngine script = ScriptFactory
                    .getScriptEngine(ScriptFactory.VELOCITY);
            script.put("place", p);
            script.put("placeState", placeState);
            script.put("ticket", new TicketWarp(t));
            String printXml = script.eval(sresource).toString();
            m_TTP.printTicket(printXml);
            textPane.setText("");
        } catch (ScriptException e) {
            MessageInf msg = new MessageInf(MessageInf.SGN_WARNING,
                    AppLocal.getIntString("message.cannotprintticket"), e);
            msg.show(this);
        } catch (TicketPrinterException e) {
            MessageInf msg = new MessageInf(MessageInf.SGN_WARNING,
                    AppLocal.getIntString("message.cannotprintticket"), e);
            msg.show(this);
        }
    }


    protected void setPlaceClickState(boolean state) {
        clickStateFlag = state;
        tgChangeStateButton.setSelected(clickStateFlag);
    }

    @Override
    public JComponent getBagComponent() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void showNextTicket() {

    }

    @Override
    public void showPrevTicket() {

    }


}
